//
//  MemoryManagementTest.m
//  iOS Sample Code
//
//  Created by lei yu on 11-12-9.
//  Copyright (c) 2011年 lancet. All rights reserved.
//

#import "MemoryManagementTest.h"



@implementation MemoryManagementTest

// All code under test must be linked into the Unit Test bundle
- (void)testReferenceCounting
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    NSNumber *myInt = [[NSNumber alloc] initWithInteger: 100];                  
    
    NSNumber  *myInt2;
    NSMutableArray  *myArr = [NSMutableArray array];
    NSLog (@"myInt retain count = %lx", (unsigned long) [myInt retainCount]);
    [myArr addObject: myInt];
    NSLog (@"after adding to array = %lx",(unsigned long) [myInt retainCount]);
    myInt2 = myInt;
    NSLog (@"after asssignment to myInt2 = %lx",(unsigned long) [myInt retainCount]);
    [myInt retain];
    NSLog (@"myInt after retain = %lx",(unsigned long) [myInt retainCount]); NSLog (@"myInt2 after retain = %lx",(unsigned long) [myInt2 retainCount]);
    
    [myInt release];
    NSLog (@"after release = %lx",(unsigned long) [myInt retainCount]);
    [myArr removeObjectAtIndex: 0];
    NSLog (@"after removal from array = %lx",(unsigned long) [myInt retainCount]);
    [myInt2 release]; 
    [pool drain];
}


/*
 
 Constant strings use no reference-counting mechanism because they can never be released.This is why when the retainCount message is sent to myStr1, it returns a value of 0xfffffffffffffff.
 Notice that the same applies to an immutable string object that is initialized with a con- stant string: It, too, has no meaningful retain count.
 
 */

-(void)testReferenceCountingOfString{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSString  *myStr1 = @"Constant string";
    NSString *myStr2 = [NSString stringWithString: @"string 2"];
    NSMutableString *myStr3 = [NSMutableString stringWithString: @"string 3"];
    NSMutableArray *myArr = [NSMutableArray array];
    NSLog (@"Retain count: myStr1: %lx, myStr2: %lx, myStr3: %lx", (unsigned long) [myStr1 retainCount],(unsigned long) [myStr2 retainCount],(unsigned long) [myStr3 retainCount]);
    [myArr addObject: myStr1]; [myArr addObject: myStr2]; [myArr addObject: myStr3];
    NSLog (@"Retain count: myStr1: %lx, myStr2: %lx, myStr3: %lx", (unsigned long) [myStr1 retainCount],(unsigned long) [myStr2 retainCount],(unsigned long) [myStr3 retainCount]);
    [myStr1 retain]; 
    [myStr2 retain];
    [myStr3 retain];
    NSLog (@"Retain count: myStr1: %lx, myStr2: %lx, myStr3: %lx", (unsigned long) [myStr1 retainCount],(unsigned long) [myStr2 retainCount],(unsigned long) [myStr3 retainCount]);
    // Bring the reference count of myStr3 back down [myStr3 release];
    [pool drain];
   
}

@end
